<template>
    <Header></Header>

    <div class="container mx-auto max-w-screen-xl mt-5 px-4 py-6 bg-gradient-to-b from-blue-50 to-white">
        <div class="grid grid-cols-4 gap-6">
            <!-- 左边栏 -->
            <div class="col-span-4 px-3 md:col-span-3 sm:col-span-4">
                <h1 class="text-3xl font-bold mb-6 text-indigo-800 relative inline-block">
                    <span class="relative z-10">文章归档</span>
                    <span class="absolute left-0 bottom-1 w-full h-2 bg-yellow-300 opacity-50 rounded-full"></span>
                </h1>
                
                <div v-if="archives && archives.length > 0">
                    <div v-for="(yearGroup, year) in groupedArchives" :key="year" class="mb-10">
                        <h2 class="text-2xl font-bold mb-4 text-indigo-700">{{ year }}</h2>
                        
                        <div v-for="(item, index) in yearGroup" :key="index"
                            class="p-5 mb-4 border border-indigo-50 rounded-lg bg-white shadow-md dark:bg-gray-800 dark:border-gray-700">
                            <time class="text-xl font-semibold text-indigo-600 dark:text-white">{{ item.month }}</time>
                            <ol class="mt-3 divide-y divider-gray-200 dark:divide-gray-700">
                                <li v-for="(article, articleIndex) in item.articles" :key="articleIndex">
                                    <a @click="goArticleDetail(article.id)"
                                        class="cursor-pointer items-center block p-3 sm:flex hover:bg-indigo-50 rounded-lg transition-colors duration-200 dark:hover:bg-gray-700">
                                        <img class="w-24 h-16 mb-3 mr-3 rounded-lg sm:mb-0 object-cover" 
                                            :src="article.titleImage || article.cover || article.title_image || 'https://via.placeholder.com/800x400?text=暂无封面'"
                                            @error="$event.target.src='https://via.placeholder.com/800x400?text=暂无封面'" 
                                            alt="文章封面" />
                                        <div class="text-gray-600 dark:text-gray-400 flex-1">
                                            <div class="text-base font-normal">
                                                <span class="font-medium text-gray-900 dark:text-white hover:text-indigo-600 transition-colors duration-300">
                                                    {{ article.title }}
                                                </span>
                                            </div>
                                            <span class="inline-flex items-center text-xs font-normal text-indigo-500 dark:text-gray-400">
                                                <svg class="w-3 h-3 mr-1" aria-hidden="true"
                                                    xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 20 20">
                                                    <path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round"
                                                        stroke-width="2"
                                                        d="M5 1v3m5-3v3m5-3v3M1 7h18M5 11h10M2 3h16a1 1 0 0 1 1 1v14a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Z" />
                                                </svg>
                                                {{ formatDate(article.createTime) }}
                                            </span>
                                        </div>
                                    </a>
                                </li>
                            </ol>
                        </div>
                    </div>
                </div>
                <div v-else>
                    <div class="flex flex-col items-center mb-5">
                        <svg xmlns="http://www.w3.org/2000/svg" class="w-24 h-24 text-indigo-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
                        </svg>
                        <p class="text-indigo-500 mt-5 text-lg font-bold">暂无文章归档</p>
                    </div>
                </div>
            </div>
            <!-- 右边栏 -->
            <div class="col-span-4 px-3 md:col-span-1 sm:col-span-4">
                <div class="sticky top-21 space-y-6">
                    <UserInfoCard></UserInfoCard>
                    
                    <!-- 文章分类 -->
                    <div
                        class="w-full font-medium p-5 bg-white border border-indigo-50 rounded-lg shadow-md border-t-4 border-yellow-500 dark:bg-gray-800 dark:border-gray-700">
                        <h2 class="mb-4 font-bold text-indigo-700 uppercase dark:text-white">分类</h2>
                        <div>
                            <a @click="goCategoryArticleListPage(item.id, item.name)" v-for="(item, index) in categories"
                                :key="index"
                                class="inline-block bg-yellow-50 text-yellow-600 text-xs font-medium mr-2 mb-2 px-2.5 py-1 rounded hover:bg-yellow-100 transition-colors duration-200 dark:hover:bg-yellow-800 dark:hover:text-yellow-300 dark:bg-yellow-900 dark:text-yellow-300">
                                {{ item.name }}
                            </a>
                        </div>
                    </div>
                    
                    <!-- 文章标签 -->
                    <div
                        class="w-full font-medium p-5 bg-white border border-indigo-50 rounded-lg shadow-md border-t-4 border-indigo-500 dark:bg-gray-800 dark:border-gray-700">
                        <h2 class="mb-4 font-bold text-indigo-700 uppercase dark:text-white">热门标签</h2>
                        <div @click="goTagArticleListPage(item.id, item.name)" v-for="(item, index) in tags" :key="index"
                            class="inline-block bg-indigo-50 text-indigo-600 text-xs font-medium mr-2 mb-2 px-2.5 py-1 rounded hover:bg-indigo-100 transition-colors duration-200 dark:hover:bg-indigo-800 dark:hover:text-indigo-300 dark:bg-indigo-900 dark:text-indigo-300">
                            {{ item.name }}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <Footer></Footer>
</template>

<script setup>
import Header from '@/layouts/components/Header.vue'
import Footer from '@/layouts/components/Footer.vue'
import UserInfoCard from '@/components/UserInfoCard.vue'
import { useRouter } from 'vue-router'
import { getArchives } from '@/api/frontend/archive'
import { getTags } from '@/api/frontend/tag'
import { getCategories } from '@/api/frontend/category'
import { ref, computed } from 'vue'

const router = useRouter()

const goArticleDetail = (articleId) => {
    console.log('跳转详情页' + articleId)
    router.push({ path: '/article/detail', query: { articleId: articleId } })
}

const goTagArticleListPage = (id, name) => {
    router.push({ path: '/tag/list', query: { id: id, name: name } })
}

const goCategoryArticleListPage = (id, name) => {
    router.push({ path: '/category/list', query: { id: id, name: name } })
}

const archives = ref([])
const tags = ref([])
const categories = ref([])

// 按年份分组归档数据
const groupedArchives = computed(() => {
    const grouped = {}
    
    archives.value.forEach(archive => {
        const year = archive.month.split('-')[0]
        if (!grouped[year]) {
            grouped[year] = []
        }
        grouped[year].push(archive)
    })
    
    // 对每个年份的数据按月份倒序排序
    Object.keys(grouped).forEach(year => {
        grouped[year].sort((a, b) => b.month.localeCompare(a.month))
    })
    
    // 返回按年份倒序排序的对象
    return Object.keys(grouped)
        .sort((a, b) => b.localeCompare(a))
        .reduce((acc, year) => {
            acc[year] = grouped[year]
            return acc
        }, {})
})

// 格式化日期，显示为2023-10-25格式
const formatDate = (dateStr) => {
    if (!dateStr) return ''
    // 如果日期格式为2023-10-25 12:34:56，只保留日期部分
    return dateStr.split(' ')[0]
}

// 获取归档数据
function getArchiveList() {
    console.log('获取归档数据')
    getArchives({})
        .then((res) => {
            console.log('归档数据响应:', res)
            if (res.success) {
                archives.value = res.data
                console.log(`获取到${archives.value.length}个归档月份`)
                console.log('归档数据:', JSON.stringify(archives.value))
            } else {
                console.error('获取归档数据失败:', res.message)
            }
        })
        .catch(err => {
            console.error('获取归档数据出错:', err)
        })
}
getArchiveList()

// 获取标签
getTags().then((e) => {
    console.log('获取标签数据')
    if (e.success) {
        tags.value = e.data
    }
}).catch(err => {
    console.error('获取标签数据出错:', err)
})

// 获取分类
getCategories().then((e) => {
    console.log('获取分类数据')
    if (e.success) {
        categories.value = e.data
    }
}).catch(err => {
    console.error('获取分类数据出错:', err)
})
</script>

<style scoped>
.container {
    max-width: 1230px;
}
</style>